<?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
class IndexController extends Controller
{
    //首页
    public function index(){
        return view('kexue.w_index',['assign'=>getDefault(),'bar'=>bar()]);
    }
    //注册
    public function register(Request $request){
        $data = $request->post();
        $rules = [
            'member_name'=>'required|min:2',
            'phone'=>'required',
            'email'=>'required|email',
            'password'=>'required',
            'work_company'=>'required',
            'post'=>'required',
            'objective'=>'required',
        ];
        $messages = [
            'required'=>':attribute 为必填项',
            'min'=>':attribute 长度不符合要求',
            'email'=>':attribute 格式错误',
        ];
        $validator = Validator::make($data,$rules,$messages,[
            'member_name'=>'用户名称',
            'email'=>'Email'
        ]);
        if($validator->fails()){
            return response()->json(['code'=>0,'msg'=>$validator->errors()->first()]);
        }else{
            if ($data['password'] != $data['confirm_password']){
                return response()->json(['code'=>0,'msg'=>'两次密码不正确']);
            }
            $arr = DB::table('admin_member')->where('member_name','=',$data['member_name'])->first();
            if ($arr){
                return response()->json(['code'=>0,'msg'=>'用户名已被注册']);
            }
            unset($data['confirm_password']);
            $data['password'] = sha1($data['password']);
            $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s');
            $res = DB::table('admin_member')->insert($data);
            if ($res){
                return ['code'=>200,'msg'=>'注册成功,请登录'];
            }else{
                return ['code'=>0,'msg'=>'注册失败'];
            }
        }

    }
    //登录
    public function login(Request $request){
        $data = $request -> post();
        $arr = DB::table('admin_member')->where('member_name','=',$data['member_name'])->first();
        if (!$arr){
            return response()->json(['code'=>0,'msg'=>'用户名不存在']);
        }
        if(sha1($data['password']) != $arr -> password){
            return response()->json(['code'=>0,'msg'=>'密码不正确']);
        }
        if(!$arr->status){
            return response()->json(['code'=>0,'msg'=>'用户已禁用']);
        }
        session(['member_id' => $arr->member_id]);
        return response()->json(['code'=>200,'msg'=>'登录成功']);
    }
    //退出登录
    public function loginOut(){
        session(['member_id' => '']);
    }
}
